<template>
  <div class="container" v-loading="loading" element-loading-text="Excel数据导出中，请耐心等待......" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-row type="flex" justify="space-between">
      <div style="display:flex;flex:1">
        <el-button @click="exportExcel" type="success" icon="el-icon-download">导出</el-button>
      </div>
      <div style="display:flex;justify-content: flex-end;align-items:center;flex:12">
        <el-select v-model="selectNetCode" placeholder="请选择台网码" style="margin-left: 1%;width: 13%;">
          <el-option v-for="item in netCodeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="selectChanNum" placeholder="请选择位置号" style="margin-left: 1%;width: 13%;">
          <el-option v-for="item in chanNumOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="selectChanCode" placeholder="请选择通道码" style="margin-left: 1%;width: 13%;">
          <el-option v-for="item in chanCodeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <span style="font-size: 14px;width: 4%">设定:</span>
        <el-input v-model="intSettingThreshold" style="width: 20%" class="input-with-select" type="number">
          <el-select v-model="settingLessThanSymbol" slot="prepend" placeholder="阈值" style="width: 110px">
            <el-option label="大于等于" value="大于等于"></el-option>
            <el-option label="小于等于" value="小于等于"></el-option>
          </el-select>
        </el-input>
        <span style="font-size: 14px;width: 4%">筛选: </span>
        <el-input v-model="intFilteredThreshold" style="width: 20%" class="input-with-select" type="number">
          <el-select v-model="filteredLessThanSymbol" slot="prepend" placeholder="阈值" style="width: 110px">
            <el-option label="大于等于" value="大于等于"></el-option>
            <el-option label="小于等于" value="小于等于"></el-option>
          </el-select>
        </el-input>
        <el-date-picker style="margin-left: 10px;width: 25%;" v-model="date"
                        type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"  value-format="yyyy-MM-dd">
        </el-date-picker>
      </div>
      <div style="display:flex; justify-content: flex-end;flex:2">
        <el-button style="margin-left: 10px" @click="queryData" type="primary" icon="el-icon-search">查询</el-button>
        <el-button style="margin-left: 10px" @click="clearFn" type="danger" icon="el-icon-delete">清除</el-button>
      </div>
    </el-row>

    <el-table :data="tableData" style="width: 100%;margin-top:15px;" border :cell-style="cellStyle" :row-style="{height:'40px'}"
              v-loading="tableLoading" element-loading-text="数据加载中，请耐心等待......" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.6)">
      <el-table-column prop="netCode" label="台网" align="center">
      </el-table-column>
      <el-table-column prop="staCode" label="台站代码" align="center">
      </el-table-column>
      <el-table-column prop="fullCode" label="台站完整代码" align="center">
      </el-table-column>
      <el-table-column prop="typeName" label="台站类型" align="center">
      </el-table-column>
      <el-table-column prop="avgRate" label="次数" align="center">
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import { getBreakData, getAllNetCode, getAllChanNum, getAllChanCode, getNetCode, exportBreak } from '@/api'
export default {
  name: 'Home',
  data () {
    return {
      tableData: [],
      netCode: [],
      pageInfo: {
        endDate: '',
        pageNum: 1,
        pageSize: 10,
        startDate: ''
      },
      netCodeOptions: [],
      chanNumOptions: [],
      chanCodeOptions: [],
      selectChanCode: '',
      selectChanNum: '',
      selectNetCode: '',
      date: '',
      total: 0,
      settingLessThanSymbol: '大于等于', // 大于-false 小于-true
      filteredLessThanSymbol: '大于等于', // 大于-false 小于-true
      intSettingThreshold: 0, // 阈值
      intFilteredThreshold: 0, // 阈值
      loading: false,
      tableLoading: false
    }
  },
  created () {
    // this.getTable3Data()
    const dateRange = this.getDefaultDate()
    this.pageInfo.startDate = dateRange[0]
    this.pageInfo.endDate = dateRange[1]
    this.date = [dateRange[0], dateRange[1]]
    this.getBaseData()
    this.getList()
    this.getNetCode()
  },
  methods: {
    async getBaseData () {
      const { data: { data: data1 } } = await getAllNetCode()
      this.netCodeOptions = data1.map(item => ({ value: item, label: item }))
      const { data: { data: data2 } } = await getAllChanNum()
      this.chanNumOptions = data2.map(item => ({ value: item, label: item }))
      const { data: { data: data3 } } = await getAllChanCode()
      this.chanCodeOptions = data3.map(item => ({ value: item, label: item }))
    },
    async getNetCode () {
      const { data: { data } } = await getNetCode()
      this.netCode = data
    },
    async getList () {
      // 数据组装
      this.tableLoading = true
      this.queryInfo = {
        ...this.pageInfo,
        netCode: this.selectNetCode,
        chanNum: this.selectChanNum,
        chanCode: this.selectChanCode,
        intSettingThreshold: this.intSettingThreshold,
        intFilteredThreshold: this.intFilteredThreshold,
        settingLessThanSymbol: this.settingLessThanSymbol === '小于',
        filteredLessThanSymbol: this.filteredLessThanSymbol === '小于'
      }
      const { data: { data } } = await getBreakData(this.queryInfo)
      console.log(data)
      this.tableData = data.records
      this.total = data.total
      console.warn(data)
      this.tableLoading = false
    },
    getDefaultDate () {
      const date = new Date()// 当前时间
      const year = date.getFullYear() // 返回指定日期的年份
      const month = this.repairDate(date.getMonth() + 1)// 月
      const day = this.repairDate(date.getDate())// 日

      // 当前时间
      const endDate = year + '-' + month + '-' + day

      const date2 = new Date(date)
      date2.setDate(date2.getDate() - 6)
      const year2 = date2.getFullYear() // 返回指定日期的年份
      const month2 = this.repairDate(date2.getMonth() + 1)// 月
      const day2 = this.repairDate(date2.getDate())// 日
      const startDate = year2 + '-' + month2 + '-' + day2
      const dateRange = [startDate, endDate]

      return dateRange
    },
    repairDate (i) {
      if (i >= 0 && i <= 9) {
        return '0' + i
      } else {
        return i
      }
    },
    handleSizeChange (newSize) {
      this.pageInfo.pageSize = newSize
      this.getList()
    },
    handleCurrentChange (newNum) {
      this.pageInfo.pageNum = newNum
      this.getList()
    },
    queryData () {
      if (this.date) {
        this.pageInfo.startDate = this.date[0]
        this.pageInfo.endDate = this.date[1]
      }
      this.pageInfo.pageNum = 1
      this.pageInfo.pageSize = 10
      this.getList()
    },
    clearFn () {
      this.pageInfo = {
        endDate: '',
        pageNum: 1,
        pageSize: 10,
        startDate: ''
      }
      this.selectChanNum = ''
      this.selectNetCode = ''
      this.selectChanCode = ''
      this.intSettingThreshold = 0
      this.intFilteredThreshold = 0
      this.settingLessThanSymbol = '大于等于' // 大于-false 小于-true
      this.filteredLessThanSymbol = '大于等于' // 大于-false 小于-true
      this.getList()
    },
    // 表格颜色
    cellStyle ({ row, column, rowIndex }) {
      if (column.label === '次数' && row.statusColorEnum === '绿色') {
        return 'background:#00FF7F;color:black;padding:0px'
      } else if (column.label === '次数' && row.statusColorEnum === '黄色') {
        return 'background:#ffeb9c;color:black;padding:0px'
      } else if (column.label === '次数' && row.statusColorEnum === '红色') {
        return 'background:#f56c6c;color:black;padding:0px'
      }
      return 'padding:0px'
    },
    async exportExcel () {
      if (!this.date) return this.$message.error('请指定导出范围~')
      this.loading = true

      // 包裹多表数据变量定义
      const allHeader = []
      const allMerges = []
      const allData = []
      const allSheetName = []
      const dic = new Map()
      const allColorCol = []// sheet1全为空，sheet是每一行对应的需要变的颜色

      // 解决forEach异步问题
      const promiseArray = []

      const queryInfo = {
        endDate: this.date[1],
        startDate: this.date[0],
        pageNum: 1,
        pageSize: -1,
        netCode: '',
        chanNum: this.selectChanNum,
        chanCode: this.selectChanCode,
        intSettingThreshold: this.intSettingThreshold,
        intFilteredThreshold: this.intFilteredThreshold,
        settingLessThanSymbol: this.settingLessThanSymbol === '小于等于',
        filteredLessThanSymbol: this.filteredLessThanSymbol === '小于等于'
      }
      const header2 = ['台网', '台站代码', '台站完整代码', '台站类型', '台站类型', '次数'] // 标题

      let netCodes = []
      if (this.selectNetCode === '') {
        netCodes = this.netCode
      } else {
        netCodes.push(this.selectNetCode)
      }

      // 获取数据,有多个台网的，这里先做一个的测试
      netCodes.forEach(async netCode => {
        queryInfo.netCode = netCode
        const p = new Promise((resolve, reject) => {
          const sheet = {
            header: [],
            data: [],
            colorCol: []
          }
          exportBreak(queryInfo).then(({ data: { data } }) => {
            // console.clear()
            console.log(data)
            // 表头组装-（最终是由多个台网构成的[[],[],[]])
            let staCode = []
            if (data.length > 0) {
              staCode = data[0].dataList.map(item => item.staCode + '_' + item.chanNum)
            }
            sheet.header = ['日期      ', ...staCode]
            // 数据组装,data数组有多长，说明就有几天的，也就是说有几行的数据
            data.forEach(item => {
              const row = item.dataList.map(itemIn => itemIn.status)
              row.unshift(item.date) // 日期
              sheet.data.push(row)
            })
            allMerges.push([])
            dic.set(netCode + '_1', sheet)
            // 代表本次执行完
            resolve()
          })
        })
        // 收集进去promise数组
        promiseArray.push(p)
        const s = new Promise((resolve, reject) => {
          const sheet = {
            header: header2,
            data: [],
            colorCol: []
          }
          getBreakData(queryInfo).then(({ data: { data } }) => {
            // 数据组装,data数组有多长，说明就有几天的，也就是说有几行的数据
            console.log(data)
            sheet.colorCol = data.records.map(item => item.statusColorEnum)

            data.records.forEach(item => {
              var row = []
              const obj = JSON.parse(JSON.stringify(item, ['netCode', 'staCode', 'fullCode', 'staForType',
                'typeName', 'avgRate'], 4))
              for (var a in obj) {
                row.push(obj[a])
              }
              sheet.data.push(row)
            })
            allMerges.push([])
            dic.set(netCode + '_2', sheet)
            // 代表本次执行完
            resolve()
          })
        })
        promiseArray.push(s)
      })

      Promise.all(promiseArray).then(() => {
        netCodes.forEach(async netCode => {
          const sheetName1 = netCode + '_1'
          const sheet1 = dic.get(sheetName1)
          allHeader.push(sheet1.header)
          allData.push(sheet1.data)
          allSheetName.push(sheetName1)
          allColorCol.push(sheet1.colorCol)
          const sheetName2 = netCode + '_2'
          const sheet2 = dic.get(sheetName2)
          console.log(sheet1)
          allHeader.push(sheet2.header)
          allData.push(sheet2.data)
          allSheetName.push(sheetName2)
          allColorCol.push(sheet2.colorCol)
        })

        import('@/utils/exportAllShert').then(excel => {
          excel.export_json_to_excel({
            // header: [header],
            header: allHeader,
            // data: [[['鹿琛', '12']], [['尘世', '18']]],
            // data: [tableData],
            data: allData,
            filename: '断记次数超标',
            autoWidth: true,
            // merges: [[]],
            merges: allMerges,
            SheetNames: allSheetName,
            bookType: 'xlsx',
            colorCol: '次数',
            colorColData: allColorCol
          })
          setTimeout(() => {
            this.loading = false
          }, 3000)
        })
      })
    }

  }
}
</script>
<style lang="less" scoped>
.page {
  margin-top: 20px;
}

</style>
